package dao

import (
	"fmt"
	"strings"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/priceslog"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 登录日志相关操作 -----------------------//

type PlacePriceLogsDao struct {
}

func NewPlacePriceLogsDao() *PlacePriceLogsDao {
	return &PlacePriceLogsDao{}
}

// 网点修改计费日志
func (d *PlacePriceLogsDao) InsertPlacePriceLogs(m *priceslog.PriceLogModel) *dingo.ErrorWrap {

	db := global.Orm.Debug().Table("place_price_log").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// GetLoginLogsList            登录日志查询列表
func (d *PlacePriceLogsDao) GetPlacePriceLogsList(param *request.PlacePriceLogsListReq) *dingo.ErrorWrap {
	var (
		lst    []priceslog.PriceLogModelPre
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	db := global.Orm.Table("place_price_log l").
		Select("l.*,p.place_name").
		Joins("left join places p on l.place_id = p.id")

	//用户名称
	if param.UserName != "" {
		db.Where("l.user_name like ?", fmt.Sprint("%", param.UserName, "%"))
	}

	//网点名称
	if param.PlaceName != "" {
		db.Where("p.place_name like ?", fmt.Sprint("%", param.PlaceName, "%"))
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		fmt.Println("beginTime: ", beginTime[0], beginTime[1])
		db.Where("DATE_FORMAT(FROM_UNIXTIME(l.create_at),'%Y-%m-%d') >=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d') and "+
			"DATE_FORMAT(FROM_UNIXTIME(l.create_at),'%Y-%m-%d')<=  DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", beginTime[0], beginTime[1])
	}
	db.Order("create_at desc")
	//log.Println("GetPlaceList 执行的SQL: ",)
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}
